package com.vinci.task.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vinci.login.entity.TbLoginUser;
import com.vinci.task.entity.TbTaskInfo;
import com.vinci.task.entity.TbTaskReply;
import com.vinci.task.mapper.TbTaskInfoMapper;
import com.vinci.task.mapper.TbTaskReplyMapper;
import com.vinci.task.service.TbTaskReplyService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张先生
 * @since 2021-12-13
 */
@Service
public class TbTaskReplyServiceImpl extends ServiceImpl<TbTaskReplyMapper, TbTaskReply> implements TbTaskReplyService {

    @Autowired(required = false)
    private TbTaskReplyMapper tbTaskReplyMapper;
    @Autowired(required = false)
    private TbTaskInfoMapper tbTaskInfoMapper;

    /**
     * 添加回复表
     * @param tbTaskReply
     */
    @Override
    public void insertTbTaskReply(TbTaskReply tbTaskReply, HttpSession session) {

        try {
            TbLoginUser user = (TbLoginUser) session.getAttribute("user");
            String realName = user.getRealName();
            String userId = user.getUserId();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            tbTaskReply.setTaskId(uuid);
            tbTaskReply.setCreateBy(userId);
            tbTaskReply.setCreateTime(new Timestamp(System.currentTimeMillis()));
            tbTaskReply.setUpdateTime(new Timestamp(System.currentTimeMillis()));

            TbTaskInfo task = new TbTaskInfo();
            task.setStatus(4);
            String taskId = tbTaskReply.getTaskId();
            task.setTaskId(taskId);

            // 1. 创建ProcessEngine
            ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
            // 获取taskService
            TaskService taskService = processEngine.getTaskService();

            //根据流程key 和 任务负责人 查询任务
            // 返回一个任务对象
            Task task2 = taskService.createTaskQuery()
                    .processDefinitionKey("task_info") //流程key
                    .taskAssignee(realName) //要查询的负责人
                    .singleResult();
            if(task2 != null){
                // 根据任务id来   完成任务
                taskService.complete(task2.getId());
            }

            tbTaskInfoMapper.updateClaim(task);
            tbTaskReplyMapper.insertTbTaskReply(tbTaskReply);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
